<template>
  <div class="app-container">
    <!--查询-->
    <el-row>
      <el-input style="width:200px;margin-right: 10px" v-model="tableQuery.name" placeholder="分组名称"></el-input>
      <el-tooltip class="item" content="搜索" placement="top">
        <el-button icon="el-icon-search" circle @click="fetchData()"></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px;"></div>
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate">{{textMap.create}}</el-button>
    <el-tooltip content="标签分组导入" placement="top">
      <el-button size="mini" type="primary" @click="fileImpt"><svg-icon icon-class="f-import" class-name="im-ex-icon" /> 导入</el-button>
    </el-tooltip>
    <el-tooltip content="标签分组导出" placement="top">
      <el-button size="mini" type="primary" @click="fileExptAll"><svg-icon icon-class="f-export" class-name="im-ex-icon" /> 全部导出</el-button>
    </el-tooltip>
    <el-tooltip content="统标签分组选择导出" placement="top" v-if="batchOperate">
      <el-button size="mini" type="primary" @click="fileExpt"><svg-icon icon-class="f-export" class-name="im-ex-icon" /> 导出选择({{selectionRows.length}})</el-button>
    </el-tooltip>
    <el-tooltip content="标签分组批量删除" placement="top" v-if="batchOperate">
      <el-button size="mini" type="primary" @click="batchDelete"><svg-icon icon-class="f-export" class-name="im-ex-icon" /> 删除选择({{selectionRows.length}})</el-button>
    </el-tooltip>
    <div style="margin-bottom: 30px;"></div>
    <!--列表-->
    <el-table style="width: 100%"
              ref="groupTable"
              :data="tableData"
              v-loading.body="tableLoading"
              row-key="id"
              element-loading-text="Loading"
              @selection-change="tbSelChange"
              border fit highlight-current-row>
      <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="name" label="分组名称" ></el-table-column>
      <el-table-column prop="description" label="描述" ></el-table-column>
      <el-table-column prop="created_at" label="创建时间" ></el-table-column>
      <el-table-column prop="updated_at" label="更新时间" ></el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-tooltip content="分组编辑" placement="top">
            <el-link icon="el-icon-edit" @click="handleUpdate(scope.$index,scope.row)" >编辑</el-link>
          </el-tooltip>
          <span style="margin:10px" v-perm="['user-update']">|</span>
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{label:'bind',data:scope.row,index:scope.$index}" >标签绑定</el-dropdown-item>
              <el-dropdown-item :command="{label:'delete',data:scope.row,index:scope.$index}">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px;"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[20, 30, 40, 50, 60]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total">
    </el-pagination>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="150px" >
        <el-form-item label="分组ID" prop="id" v-if="dialogStatus=='update'">
          <el-input v-model="temp.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="分组名称" prop="name" >
          <el-input v-model="temp.name"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input type="number" v-model="temp.sort"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="en_name">
          <el-input v-model="temp.description"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" v-if="dialogStatus=='update'">
          <el-input v-model="temp.created_at" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间" v-if="dialogStatus=='update'">
          <el-input v-model="temp.updated_at" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <bind-comp :oper="dialogMap" />
    <el-dialog append-to-body :visible.sync="imptDialogVisible">
      <el-tag style="text-decoration: underline;cursor: pointer" @click.native="downloadTemp">模板下载</el-tag>
      <upload-excel @on-selected-file="uploadCallBack" />
    </el-dialog>

  </div>
</template>

<script>

  import {resetTemp,parseTime } from '@/utils'
  import { pageParamNames, confirm, root } from '@/utils/constants'
  import debounce from 'lodash/debounce'
  import uploadExcel from '@/components/UploadExcel'
  import {mapGetters} from 'vuex'
  import bindComp from './bindComp'
  import tagApi from "@/api/tag";


  export default {
    name: 'report-groups',
    components:{
      bindComp,
      uploadExcel
    },
    computed:{
      ...mapGetters([
        'token'
      ]),
      batchOperate(){
        return this.selectionRows.length>0
      }
    },
    data() {
      return {
        tableLoading:false,
        imptDialogVisible:false,
        tableData: [],
        selectionRows:[],
        tableQuery:{
          name: null
        },
        tablePage: {
          current: null,
          pages: null,
          size:null,
          total: null
        },
        dialogFormVisible: false,
        dialogStatus: '',
        dialogMap:{
          dcsBindShow:false,
          groupId:null,
          groupName:null
        },
        temp: {
          idx: null,//表格的下标
          id:null,
          name: null,
          sort:null,
          description:null,
          created_at:null,
          updated_at:null
        },
        textMap: {
          update: '编辑',
          create: '新增'
        },
        rules: {
          name: [{ required: true, message: '必填', trigger: 'blur' }]
        },
      }
    },

    created(){
      this.fetchData()
    },

    watch:{
      //延时查询
      'tableQuery.name': debounce( function(){
        this.fetchData()
      },500),
    },//watch

    methods: {
      //分页
      handleSizeChange(val) {
        this.tablePage.size = val;
        this.fetchData();
      },
      handleCurrentChange(val) {
        this.tablePage.current = val;
        this.fetchData();
      },
      //查询
      async fetchData() {
        this.tableLoading = true
        let res = await tagApi.dcsGroupList(this.tableQuery, this.tablePage)
        let groupdata = res.data
        this.tableData = groupdata.data
        this.tablePage.total=groupdata.total
        if(!this.tablePage.current)
            this.tablePage.current=1
        if (!this.tablePage.size)
            this.tablePage.size=20
        this.tableLoading = false
      },
      //更新
      handleUpdate(idx,row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.idx = idx
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
            const tempData = Object.assign({}, this.temp)//copy obj
            tagApi.updateDcsGroup(tempData).then(res => {
              this.tableData.splice(tempData.idx, 1, tempData)
              this.dialogFormVisible = false
              this.$message.success('更新组成功')
            })
        })
      },

      //删除
      handleDelete(idx,row) {
        this.$confirm('您确定要永久删除该组？', '提示', confirm).then(() => {
          tagApi.deleteDcsGroup( row.id ).then(res => {
            this.tablePage.total--
            this.dialogFormVisible = false
            const page_surplus = this.tablePage.total % this.tablePage.size
            const max_page = Math.ceil(this.tablePage.total/this.tablePage.size)
            if (!page_surplus&&this.tablePage.current>max_page)
              this.tablePage.current--
            this.$message.success("删除成功")
            this.fetchData()
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      async batchDelete(){
        this.tableLoading=true
        for (let i=0;i<this.selectionRows.length;i++){
          const stdRow = this.selectionRows[i]
          await this.delRoop(stdRow.id)
          console.log('删除了:',stdRow.cn_name)
        }
        this.$refs['groupTable'].clearSelection()
        this.selectionRows=[]
        this.tableLoading=false
        this.$message.success("批量删除成功!")
        this.tablePage.current=1
        this.fetchData()
      },
      delRoop(gid){
        return new Promise(resolve => {
          tagApi.deleteDcsGroup( gid ).then(res => {
            resolve(res)
          })
        })
      },

      //新增
      handleCreate() {
        resetTemp(this.temp)
        this.dialogStatus = 'create'
        this.temp.sort=10
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
          tagApi.addDcsGroup(this.temp).then((res) => {
              this.dialogFormVisible = false
              this.$message.success('添加成功')
              this.fetchData()
            })
        })
      },
      bindCategroy(idx,row){
        this.dialogMap.dcsBindShow=true
        this.dialogMap.groupId=row.id
        this.dialogMap.groupName=row.name
      },
      tbSelChange(rows){
        this.selectionRows = rows
      },
      fileImpt(){
        this.imptDialogVisible=true
      },
      fileExptAll(){
        this.exptCallBack(null)
      },
      fileExpt(){
        const sids = this.selectionRows.map(row=> row.id).join(',')
        this.exptCallBack(sids)
      },
      exptCallBack(ids){
        let title = '全部内容'
        if (ids)
          title='所选内容'
        const confirmTitle=`您确定要下载${title}？`
        this.$confirm(confirmTitle, '提示', confirm).then(() => {
          this.submitDataExport(ids)
        }).catch(() => {
          this.$message({type: 'info', message: '已取消导出'});
        });
      },
      uploadCallBack(excelData){
        const confirmTitle=`您确定要上传文件${excelData.name}？`
        this.$confirm(confirmTitle, '提示', confirm).then(() => {
          this.submitDataImport(excelData)
        }).catch(() => {
          this.$message({type: 'info', message: '已取消上传'});
          this.imptDialogVisible=false
        });
      },
      submitDataExport(ids){
        console.log(ids)
        const baseHost = 'http://analysisapi.wm-mis.com/api'
        let ids_query = 'all'
        if (ids)
          ids_query = ids
        const durl = `${baseHost}/dcs-group/download?token=${this.token}&ids=${ids_query}`
        window.open((durl),"_self");
      },
      submitDataImport(excelData){
        const imptData = JSON.stringify(excelData)
        console.log(imptData)
        this.$message.success("上传成功")
        this.imptDialogVisible=false
        tagApi.imptDcsGroups(imptData).then(res=>{
            if (res.code){
              return
            }
            this.$message.success("上传成功")
            this.imptDialogVisible=false
          })
      },
      downloadTemp(){
        let tmp_url = 'http://wmhb.wm-mis.com/group-temp.xlsx'
        window.open((tmp_url),"_self");
      },
      handleCommand(comand){
        if (comand.label==='delete'){
          this.handleDelete(comand.index,comand.data)
        }else  {
          this.bindCategroy(comand.index, comand.data)
        }
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>

</style>
